/*
 * @Author: yangrongxin
 * @Date: 2021-06-08 14:30:29
 * @LastEditors: yangrongxin
 * @LastEditTime: 2021-07-23 14:47:49
 */

import { STORAGE_ERROR_TYPE, STORAGE_TYPE } from '@/const/dataDictionary';
import { setItemSync, getItemSync, removeItemSync, getInfoSync } from './storage';

/**
 * @description 缓存函数 约束名称使用Symbol进行定义
 * @author yangrongxin
 * @date 2021-06-08
 * @class Cache
 */
class Cache {
  public safeStr = [
    STORAGE_TYPE.USERINFO,
    STORAGE_ERROR_TYPE.SERVICE_NOT_WORK,
    STORAGE_TYPE.ISSHOWDEMO,
    STORAGE_TYPE.DEBUGGER_HOST,
  ]; // 保留字段
  static instance: any; // 存储当前函数的实例
  static splitSymbol: string = '$'; // 获取当前的标识符
  getInstance() {
    if (!Cache.instance) {
      Cache.instance = new Cache();
    }
    return Cache.instance;
  }

  static joinNameAndParams(name, params) {
    return `${name}${Cache.splitSymbol}${JSON.stringify(params)}`;
  }

  /**
   * @description 根据缓存名称获取缓存信息
   * @author yangrongxin
   * @date 2021-06-08
   * @param {*} name 当前请求的url名称
   * @param {*} params 当前请求url名称的参数
   * @param {*} responseData 返回的请求体中data的数据
   * @memberof Cache
   */
  saveCacheWidthName(name, params, responseData) {
    setItemSync(Cache.joinNameAndParams(name, params), responseData);
  }

  /**
   * @description 根据缓存名称和请求参数获取对应的缓存信息
   * @author yangrongxin
   * @date 2021-06-08
   * @memberof Cache
   */
  getCacheWithName(name, params) {
    return getItemSync(Cache.joinNameAndParams(name, params));
  }

  /**
   * @description 根据名称删除对应的缓存信息
   * @author yangrongxin
   * @date 2021-06-08
   * @memberof Cache
   */
  removeCacheWithName(name, params) {
    removeItemSync(Cache.joinNameAndParams(name, params));
  }

  /**
   * @description 清空除了登录信息以外的缓存信息
   * @author yangrongxin
   * @date 2021-06-09
   * @memberof Cache
   */
  clearCache() {
    const { keys } = getInfoSync();
    keys.forEach((item: string) => {
      if (!this.safeStr.includes(item)) removeItemSync(item);
    });
  }
}

export default new Cache().getInstance();
